package com.search;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.search.tools.MD5EncryptTool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

public class Md5Demo {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ClientType","XCX");
        jsonObject.put("NonceStr","8e1bd713-482d-48b5-8723-6982d5112e61");
        jsonObject.put("Token","5F2139E145E44642BD6B5A1A0BAD6466");
        jsonObject.put("BookName","自由民主的理路");
        jsonObject.put("IsHave",0);
        jsonObject.put("PageIndex",1);

        List<String> keys = new ArrayList<>(jsonObject.keySet());
        Collections.sort(keys);

        // 使用LinkedHashMap来保持顺序
        LinkedHashMap<String, Object> orderedMap = new LinkedHashMap<>();
        for (String key : keys) {
            orderedMap.put(key, jsonObject.get(key));
        }

        // 将LinkedHashMap转换为JSONObject（注意：这里只是模拟，因为fastjson2可能不直接支持）
        // 你可能需要以字符串的形式输出，或者再次使用JSON.parseObject(JSON.toJSONString(orderedMap), JSONObject.class)转换回JSONObject
        JSONObject sortedJsonObject = JSON.parseObject(JSON.toJSONString(orderedMap), JSONObject.class);

        StringBuilder builder = new StringBuilder();
        for(String key :sortedJsonObject.keySet()){
            builder.append(key+"="+sortedJsonObject.get(key)+"&");
        }
        builder.append("Key="+"5F2139E145E44642BD6B5A1A0BAD6466");

        String time = System.currentTimeMillis()+"";

        String originalString = sortedJsonObject.toJSONString()+time+"a8fdad21e5c9ef44aa96e6df1404e811";

        String sign = MD5EncryptTool.encry(builder.toString()).toUpperCase();
        System.out.println(sign);
    }
}
